package com.zmn.oms.zmn.business.impl.work.autoflow.state;

import com.github.ltsopensource.core.domain.Job;
import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.manager.lts.interfaces.task.TaskManager;
import com.zmn.manager.redis.RedisManager;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.constant.RedisKeyConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.manager.utils.TaskConsts;
import com.zmn.oms.model.dto.work.modify.must.OrderAssignDTO;
import com.zmn.oms.model.dto.work.modify.other.ZsRemarkDTO;
import com.zmn.oms.model.entity.changerecord.OrderChangeRecord;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.member.OrderMember;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.mongo.distribute.PlaceAnOrderPreDistribute;
import com.zmn.oms.model.vo.work.OrderAssignVO;
import com.zmn.oms.services.interfaces.changerecord.OrderChangeRecordService;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.member.OrderMemberService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.work.OrderWorkAssignBService;
import com.zmn.oms.zmn.business.interfaces.work.autoflow.state.WorkAutoFlowBService;
import com.zmn.oms.zmn.business.interfaces.work.customwork.ZsDistributeWorkBService;
import com.zmn.oms.zmn.normal.business.interfaces.order.ZsNormalOrderBService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 类描述：分单
 *
 * @author heciqi
 * @date 2019/10/28 20:06
 */
@Slf4j
@Service("flowAssignBService")
public class FlowAssignBServiceImpl<T> implements WorkAutoFlowBService<T> {
	@Autowired
	OrderWorkService orderWorkService;
	@Autowired
	OrderDetailService orderDetailService;
	@Autowired
	OrderWorkAssignBService orderWorkAssignBService;
	@Autowired
	ZsDistributeWorkBService zsDistributeWorkBService;
	@Autowired
	OrderMemberService orderMemberService;
	@Autowired
	ZsNormalOrderBService zsNormalOrderBService;
	@Autowired
	OrderChangeRecordService orderChangeRecordService;

	@Resource
	TaskManager taskManager;
	@Resource
	private RedisManager redisManager;

	@Override
	public ResultDTO<T> condition(OrderWork orderWork) {
		if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_COMPENSATE)) {
			return ResultDTO.fail("赔偿单不可操作");
		}

		// 已确认-进行中，自动分单
		if (!Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_CONFIRM)) {
			return ResultDTO.fail("不是已确认状态");
		}

		// 已分单过的，不需要重新分单
		if (orderWork.getStatus() >= OrderStatusConsts.WORK_STATUS_ASSIGN) {
			return ResultDTO.fail("已分单过");
		}

		// 会员单，工程师审核后不能派单
		if (Objects.equals(orderWork.getSourceType(), OrderConsts.ORDER_SOURCE_TYPE_MEMBER)) {
			OrderMember orderMember = orderMemberService.findMemberByKey(orderWork.getOrderId());
			if (!Objects.isNull(orderMember)) {
				if (Objects.equals(orderMember.getReviewStatus(), OrderConsts.ORDER_MEMBER_REVIEW_STATUS_WAIT_PLAT) && Objects
						.equals(orderMember.getReviewResult(), OrderConsts.ORDER_MEMBER_REVIEW_RESULT_DOING)) {
					return ResultDTO.fail("工单需后台延保复审,不可操作");
				}
				boolean reviewSuccess = orderMember.getReviewStatus() == OrderConsts.ORDER_MEMBER_REVIEW_STATUS_PLAT_SUCCESS;
				if (reviewSuccess) {
					return ResultDTO.fail("工单为审核通过的延保订单，无法操作");
				}
			}
		}

		// 是否网格化派单
		boolean isGirdId = zsDistributeWorkBService.isGridDistribute(orderWork);
		if (isGirdId){
			return ResultDTO.fail("该订单属于平台直派，不自动分单");
		}

		// 处理返修新单自动分单
		List<OrderAssignVO> assignList = this.processReworkNewOrder(orderWork);
		// 如果不是返修新单
		if (CollectionUtil.isNullOrEmpty(assignList)) {

			OrderDetail dbOrderDetail = orderDetailService.findOrderDetailByKeySrcMaster(orderWork.getOrderId());

			// 去掉啄木鸟特殊分单逻辑，代码注释，不删  wangxiaokun 20200908
		/*List<OrderAssignVO> virtualCompanyAssignVOS = orderWorkAssignBService.listZmnAssignVirtualCompanyVO(orderWork, dbOrderDetail);
		if (CollectionUtils.isNotEmpty(virtualCompanyAssignVOS)) {
			Integer plat = virtualCompanyAssignVOS.get(0).getPlat();
			if (NumberUtil.isNotNullOrZero(plat) && !Objects.equals(plat, orderWork.getPlatWork())) {
				orderDetailService.updateOrderDetailScopeServiceByKey(orderWork.getOrderId(), GlobalConsts.NO);
				this.addAutoTurnJob(orderWork.getOrderId());
				return ResultDTO.fail("虚拟公司所在平台和服务平台不一致不能自动分单，需要先自动转单");
			}
			assignList = virtualCompanyAssignVOS;
		} else {*/

			// 工程师加单，返回加单工程师所属公司
			assignList = orderWorkAssignBService.listMasterRecommendOrderAssignVO(orderWork, dbOrderDetail);

			//}

			if (CollectionUtils.isEmpty(assignList)) {
				try {
					assignList = orderWorkAssignBService.listAssignCompany(orderWork, dbOrderDetail, true);
				} catch (Exception ex) {
					log.error("[{}]自动分派异常：{},{}", orderWork.getWorkId(), ex.getMessage(), ex);
				}
			} else {
				orderWorkAssignBService.saveDissatisfy(orderWork, assignList, OrderConsts.PRE_DISCONTENT_REASON_EIGHT, true);
			}

			if (CollectionUtils.isEmpty(assignList)) {
				log.info("[{}]没有获取到自动分配公司数据", orderWork.getWorkId());
				orderDetailService.updateOrderDetailScopeServiceByKey(orderWork.getOrderId(), GlobalConsts.NO);
				// 自动转单
				//this.addAutoTurnJob(orderWork.getOrderId());
				return ResultDTO.fail("没有获取到自动分配公司数据-自动转单");
			}

			// 若服务平台是：啄木鸟，有多个：服务商满足，并且其中只有1个信息公司，则自动分单给：信息公司
			if (Objects.equals(orderWork.getPlatWork(), GlobalConsts.PLAT_MARK_ZMN)) {
				if (assignList.size() > 1) {
					// 优先列表
					assignList = orderWorkAssignBService.listZmnPriorityAssignList(assignList, orderWork, dbOrderDetail);
				}
			}
			// 服务平台是：言而有信，有多个服务商满足，排除掉指定的服务公司
			else if (Objects.equals(orderWork.getPlatWork(), GlobalConsts.PLAT_MARK_YEYX)) {
				if (assignList.size() > 1) {
					// 优先列表
					assignList = orderWorkAssignBService.listYeyxPriorityAssignList(assignList, orderWork);
					log.debug("多个可服务公司，排除[{}]", com.zmn.oms.common.constant.CompanyConsts.YEYX_SPECIAL_MANAGE_COMPANY_ID2);
				}
			}
			// 服务平台是：川南环保
			else if (Objects.equals(orderWork.getPlatWork(), GlobalConsts.PLAT_MARK_CNHB)) {
				if (assignList.size() > 1) {
					// 优先列表
					assignList = orderWorkAssignBService.listCnhbPriorityAssignList(assignList, orderWork);
					log.debug("川南环保服务公司[{}]", assignList);
				}
			}

			orderDetailService.updateOrderDetailScopeServiceByKey(orderWork.getOrderId(), GlobalConsts.YES);
			if (assignList.size() > 1) {
				this.addOperateRemark(orderWork, OrderConsts.PRE_DISCONTENT_REASON_NINE, null);
				//orderWorkAssignBService.saveDissatisfy(orderWork, null, OrderConsts.PRE_DISCONTENT_REASON_NINE, true);
				log.info("[{}]获取到自动分配公司数量大于1", orderWork.getWorkId());
				return ResultDTO.fail("获取到自动分配公司数量大于1");
			}
		}
		OrderAssignVO orderAssignVO = assignList.get(0);
		OrderAssignDTO orderAssignDTO = new OrderAssignDTO();
		orderAssignDTO.setOrderId(orderWork.getOrderId());
		orderAssignDTO.setWorkId(orderWork.getWorkId());
		orderAssignDTO.setStatus(OrderStatusConsts.WORK_STATUS_ASSIGN);
		orderAssignDTO.setCompanyId(orderAssignVO.getCompanyId());
		orderAssignDTO.setCompanyName(orderAssignVO.getCompanyName());
		orderAssignDTO.setManageCompanyId(orderAssignVO.getManageCompanyId());
		orderAssignDTO.setManageCompanyName(orderAssignVO.getManageCompanyName());
		orderAssignDTO.setRecommendMasterId(orderAssignVO.getRecommendMasterId());
		orderAssignDTO.setOperatorId((long) GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
		orderAssignDTO.setOperator(GlobalConsts.getOperatorTypeName(GlobalConsts.OPERATE_USER_TYPE_SYSTEM));
		orderAssignDTO.setProportion(orderAssignVO.getProportion());
		this.addOperateRemark(orderWork, null, orderAssignVO.getManageCompanyId());

		return ResultDTO.success(orderAssignDTO);
	}

	@Override
	public void execute(T o) {
		try {
			orderWorkAssignBService.saveAssign((OrderAssignDTO) o);
		} catch (Exception e) {
			log.error("自动分单异常" + e.getMessage(), e);
		}
	}

	/**
	 * 添加操作备注
	 * @param orderWork
	 * @param reason
	 */
	private void addOperateRemark(OrderWork orderWork, String reason, Integer manageCompanyId){
		String redisKey = String.format(RedisKeyConsts.CHECK_MANAGE_COMPANY_KEY, orderWork.getWorkId());
		String redisValue = redisManager.get(redisKey);
		// 不是null，有预分配服务商
		if (StringUtil.isNotBlank(redisValue)) {
			String[] arr = redisValue.split("-");
			String reasonKey = String.format(RedisKeyConsts.CHECK_MANAGE_COMPANY_REASON_KEY, orderWork.getWorkId());
			String reasonValue = null;
			// 服务商不是空
			if (Objects.nonNull(manageCompanyId)){
				// 如果自动流转选择的服务商，与预分配服务商不同，则记录操作日志不满足原因
				if (!Objects.equals(manageCompanyId, Integer.valueOf(arr[0]))){
					reasonValue = redisManager.get(reasonKey);
				}
			} else {
				reasonValue = redisManager.get(reasonKey);
				if (StringUtil.isBlank(reasonValue)){
					reasonValue = reason;
				}
			}

			// 如果不满足则记录操作日志
			if (StringUtil.isNotBlank(reasonValue)){
				ZsRemarkDTO dto = new ZsRemarkDTO();
				dto.setOrderId(orderWork.getOrderId());
				dto.setWorkId(orderWork.getWorkId());
				dto.setOperator("系统");
				dto.setOperatorId(1L);
				dto.setRemark(arr[1] + "未自动分单缘由：" + reasonValue);
				zsNormalOrderBService.saveWorkRemark(dto);
			}
		}
	}

	/**
	 * 添加自动转单任务
	 *
	 * @param orderId
	 */
	private void addAutoTurnJob(Long orderId) {
		Job job = new Job();
		job.setTaskId(TaskConsts.TASK_ID_AUTO_TRRN + ":" + orderId);
		job.setParam(TaskManager.SHARD_FIELD, TaskConsts.TASK_ID_AUTO_TRRN);
		job.setParam("orderId", orderId.toString());
		taskManager.submitTask(job);
	}

	/**
	 * 处理返修新单自动分单
	 * @param orderWork
	 * @return
	 */
	private List<OrderAssignVO> processReworkNewOrder(OrderWork orderWork) {
		// 不是返修新单不处理
		if (!Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_NEW)
				|| !Objects.equals(orderWork.getChannelId(), OrderConsts.CHANNEL_ID_PLAT_REWORK_NEW_ORDER)
				|| NumberUtil.isNullOrZero(orderWork.getOriginalId())) {
			return null;
		}
		OrderWork rework = orderWorkService.findOrderWorkByKey(orderWork.getOriginalId(), orderWork.getOriginalId());
		// 源单不是返修单返回
		if (!Objects.equals(rework.getType(), OrderConsts.ORDER_TYPE_REWORK)) {
			return null;
		}
		// 不是第一次派单返回
		OrderChangeRecord orderChangeRecord = orderChangeRecordService.getChangeRecordByOrderId(orderWork.getOrderId());
		if (orderChangeRecord != null && orderChangeRecord.getFirstDistributeTime() != null) {
			return null;
		}

		// 预分配工程师信息为空返回
		PlaceAnOrderPreDistribute placeAnOrderPreDistribute = zsDistributeWorkBService.getPlaceAnOrderDistribute(orderWork.getWorkId());
		if (Objects.isNull(placeAnOrderPreDistribute)) {
			return null;
		}

		OrderAssignVO orderAssignVO = new OrderAssignVO();
		orderAssignVO.setCompanyId(rework.getCompanyId());
		orderAssignVO.setCompanyName(rework.getCompanyName());
		orderAssignVO.setManageCompanyId(rework.getManageCompanyId());
		orderAssignVO.setManageCompanyName(rework.getManageCompanyName());
		return Lists.newArrayList(orderAssignVO);
	}
}
